﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmAmenities : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        DataTable items = new DataTable();
        string curPO = "";
        string wrnEntMsg = "";
        float gtotal = 0f;

        bool qtyErr = false, prcErr = false,
            cmtErr = false,Committing = false,
            isViewing = false;

        //AutoChecker
        Timer tmr = new Timer();

        public frmAmenities()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            //txtType.SelectedIndex = 0;            
            //Start AutoCheck timer
            txtPrice.TextChanged += new EventHandler(CheckValue);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnCommit.Click += new EventHandler(btnCommit_Click);
            btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
                txtOR.Focus();
            });
            
            mnuRemoveEntry.Click += new EventHandler(mnuRemoveEntry_Click);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            btnCommit.Visible = false;
            btnAdd.Visible = false;
            
            //Load amenities before initializing tables
            //InitializeItemTable();
            //txtDescription.Focus();
            pnlForm.Enabled = false;
            txtCategory.SelectedIndex = 0;
            
            LoadAmenities();
        }
        //This will load amenities from lookup table
        void LoadAmenities()
        {
            UnityScript u = new UnityScript("LOADAMENITIES", 2);
            u.Script_Add(Script.DBPU_FETCH, "SELECT fData FROM tbllookup WHERE fKey='AMENITIES'");
            proc.Run(u);
        }
        
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 0) return;
            DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            int sel = grdItems.SelectedRows[0].Index;
            items.Rows[sel].Delete();
            t.MethodCall(CheckEntry);
        }
        void btnCommit_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
                
            Committing = true;
            States(false);
            t.MethodCall(CommitExpenses);
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtDescription.Text != "")
            {
                DataRow dr = items.NewRow();
                dr["Description"] = txtDescription.Text;
                dr["Amount"] = float.Parse(txtPrice.Text);
                dr["Amenities"] = txtType.Text;
                dr["Order Slip"] = txtOR.Text;
                dr["Category"] = txtCategory.Text;

                items.Rows.Add(dr);
                txtPrice.Text = "";
                txtDescription.Text = "";
                txtOR.Text = "";
                txtType.SelectedIndex = 0;

                t.MethodCall(CheckEntry);
            }
        }
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOADAMENITIES":
                        UnityScript amenities;
                        proc.Data_Fetch(out amenities);
                        txtType.Items.AddRange(amenities.ToList(0));
                        pnlForm.Enabled = true;
                        //Initialize Table Here
                        InitializeItemTable();
                        txtDescription.Focus();
                        if (txtType.Items.Count > 0)txtType.SelectedIndex = 0;
                        txtOR.Focus();
                        break;
                    case "COMMIT":
                        btnClose_Click(null, null);
                        break;
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        lblWarningEntry.Text = "Loaded @ " + proc.ProcEnd() + " sec.";
                        break;
                };
                if (Committing || isViewing) return;
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch(sender.ToString())
                {
                    case "CheckEntry":
                        lblWarningEntry.Text = wrnEntMsg;

                        if (prcErr)
                            txtPrice.ForeColor = Color.Red;
                        else
                            txtPrice.ForeColor = Color.Black;

                        if (!prcErr)
                            btnAdd.Visible = true;
                        else
                            btnAdd.Visible = false;

                        txtTotal.Text = gtotal.ToString("#,#0.00");
                        btnCommit.Visible = !cmtErr;
                        break;
                    case "CheckContent":
                        btnCommit.Visible = !cmtErr;
                        break;
                }
                if (Committing) return;
                tmr.Enabled = true;
            });
        }

        //Operations
        void InitializeItemTable()
        {
            items.Columns.Add("Num");
            items.Columns.Add("Amenities");
            items.Columns.Add("Order Slip");
            items.Columns.Add("Description");
            items.Columns.Add("Amount");
            items.Columns.Add("Category");

            items.Columns[0].AutoIncrementSeed = 1;
            items.Columns[0].AutoIncrement = true;
            items.Columns[0].DataType = typeof(int);

            items.Columns[4].DataType = typeof(float);
            items.Columns[4].DefaultValue = 0.00f;

            grdItems.DataSource = items;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            grdItems.Columns[4].DefaultCellStyle.Format = "#,#0.00";

            grdItems.Columns[0].Width = (grdItems.Width * 10) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 25) / 100;
        }
        void CheckEntry()
        {
            float fprice = 0f;
            string price = txtPrice.Text;
            //Check if Commit is valid
            if (items.Rows.Count != 0)
            {
                cmtErr = false;
            }
            else 
            {
                cmtErr = true;
            }
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg = "";
                wrnEntMsg += "Invalid AMOUNT value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if(!qtyErr) wrnEntMsg = "";
            }
            //Compute for the total
            gtotal = 0;
            for (int i = 0; i < items.Rows.Count; i++)
            {
                gtotal += (float)items.Rows[i]["Amount"];
            }
        }
        void CommitExpenses()
        {
            UnityScript u = new UnityScript("COMMIT", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            //Construct Expenses Items
            for (int i = 0; i < items.Rows.Count; i++)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tbldsamenities(fDescription, fDate, fAmount, fType, fOrderSlipNum, fCategory)",
                    new string[]{
                        items.Rows[i]["Description"].ToString(),
                        txtDate.Value.ToString("yyyy-MM-dd"),
                        items.Rows[i]["Amount"].ToString(),
                        items.Rows[i]["Amenities"].ToString(),
                        items.Rows[i]["Order Slip"].ToString(),
                        items.Rows[i]["Category"].ToString()
                    });
            }
            //Transaction Log
            //u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
            //    new string[]{
                    //StoreClientModule.Common.Username,
            //        "Added " + txtPONum.Text + " worth " + gtotal.ToString("#,#0.00"),
            //        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
           //     });
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
          
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grdItems.Enabled = s;
        }

        //Printing Module
        
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}